$(document).ready(function () {
	var pageTag = $("[name='pageTag']").val();
    $(".nav-item").removeClass("active");
    $("#" + pageTag).addClass("active");

    initSearch();

	$("#search-btn").on("click", function(e) {
        $('#category-book-list').html("<h4 class='text-center'>数据加载中请稍后。。。</h4>");
		e.preventDefault();
        Cookies.set('gxskSearchNameStr', $("#book-name").val(), { expires: 7, path: '' });
		fetchBookListByBookName($("#book-name").val(), 1, getPageSize());
    });


    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
      var target = $(e.target).attr("href") // activated tab
      //alert(target);
      Cookies.set('gxskSearchWay', target, { expires: 7, path: '' });
      if ("#browse-by-category" == target) {
        initSearch();
      }
    });

    $("#confirm-btn").on("click", function(e) {
		borrowBook($("#confirmData").attr("BID"), $("#confirmData").attr("BUID"));
    });

	$(document)
		.on('click', '.thumbnail-img', function(e) {
            e.preventDefault();
            //alert($(this).attr("value"));
            window.open("Book.aspx?BID="+$(this).attr("value"), "_self");      
        })
        .on('click', '.book-category', function(e) {
            Cookies.set('gxskSearchBookCategory', $(this).val(), { expires: 7, path: '' });
            Cookies.remove('gxskSearchBookCategoryPage', { path: '' });
            $('#category-book-list').html("<h4 class='text-center'>数据加载中请稍后。。。</h4>");
            e.preventDefault();
            $(".book-category").addClass("btn-default");
            $(".book-category").removeClass("btn-primary");
            $(this).addClass("btn-primary");
            fetchBookListByCategoryId($(this).val(), 1, getPageSize());   
        })
        .on('click', '.borrow-btn', function() {
        	$("#ConfirmDialogModal #confirmData").attr("BID", $(this).attr("value"));
        	$("#ConfirmDialogModal #confirmData").attr("BUID", $(this).attr("BUID"));
        	$("#ConfirmDialogModal").modal("show");
        })
});

function searchValidate() {
    return $("#search-form").validate({
        errorClass: "warning",
        errorContainer: "div.error",
        errorLabelContainer: $("#search-form div.error"),
        wrapper: "p",
        rules: {
            bookName: {
                required: true,
                minlength: 2,
            },
        },
        messages: {
            bookName: {
                required: "书名不能为空",
                minlength: "书名要大于两个字",
            },
        }
    }).form();
}

function fetchCategoryList(pagenum) {
    var selectedCategoryId = 0;
    if (Cookies.get('gxskSearchBookCategory')) {
        selectedCategoryId = Cookies.get('gxskSearchBookCategory');
    }
    // console.log(selectedCategoryId);
    $.ajax({
        type: "GET",
        url: "../Handle/OtherHandlerService.ashx?method=Get_ALL_Category",
        dataType: "json",
        success: function (data) {
            // console.log(data.rows);
            var items = data.rows;
            var outputHtml = "<div class='btn-toolbar' role='toolbar'>";
            for (var i = 0; i < items.length; i++) {
            	var btnClass = (selectedCategoryId == items[i]["Cname"])?"btn-primary":"btn-default";
            	outputHtml += "<div class='btn-group' style='padding-bottom:5px;' role='group'><button type='button' class='btn "+btnClass+" book-category' value='"+items[i]["Cname"]+"'>"+items[i]["Cname"]+"</button></div>";
            }
            outputHtml += "</div>";
            $('#category-list').html(outputHtml);
            refreshCategoryBookList(pagenum);
        }
    });
}

function fetchBookListByCategoryId(categoryName, PageIndex, PageSize) {
	$.ajax({
        type: "GET",
        data: {CategoryName: categoryName, PageIndex: PageIndex, PageSize: PageSize},
        url: "../Handle/BookHandlerService.ashx?method=Search_Book_List_From_CategoryID",
        dataType: "json",
        success: function (data) {
            if(data.rows.length == 0) {
            	$('#category-book-list').html("<p>非常抱歉！该分类下暂无书</p>");
        		return;
            }
            
            $('#category-book-list').html(getBookListOutputHtml(data.rows));
            $("#category-pagination").pagination({
                items: data.RecordCount,
                itemsOnPage: 12,
                currentPage: PageIndex,
                displayedPages: 3,
                prevText: "<",
                nextText: ">",
                onPageClick: changeCategoryBookPage,
                cssStyle: 'light-theme',
            });
        }
    });
}
function changeCategoryBookPage() {
    Cookies.set('gxskSearchBookCategoryPage', $("#category-pagination").pagination("getCurrentPage"), { expires: 7, path: '' });
    // console.log(Cookies.get('gxskSearchBookCategoryPage'));
    refreshCategoryBookList($("#category-pagination").pagination("getCurrentPage"));
}
function fetchBookListByBookName(bookName, PageIndex, PageSize) {
	if (searchValidate()) {
            $.ajax({
                type: "GET",
                url: "../Handle/BookHandlerService.ashx?method=Search_Book_List_From_BookName",
                data: {BookName: $("#book-name").val(), PageIndex: PageIndex, PageSize: PageSize},
                dataType: "json",
                success: function (data) {
                    // console.log(data);
                    if(data.rows.length == 0) {
                		$('#search-book-list').html("<p>非常抱歉！没有你要找的书！</p>");
                		return;
                    }
                    $('#search-book-list').html(getBookListOutputHtml(data.rows));
                    $("#name-pagination").pagination({
                        items: data.RecordCount,
                        itemsOnPage: 12,
                        cssStyle: 'light-theme',
                        displayedPages: 3,
                        onPageClick: changeSearchNameBookPage,
                        prevText: "<",
                        nextText: ">",
                        currentPage: PageIndex,
                    });
                }
            });
        }
}
function changeSearchNameBookPage() {
    Cookies.set('gxskSearchBookNamePage', $("#name-pagination").pagination("getCurrentPage"), { expires: 7, path: '' });
    refreshSearchBookList($("#name-pagination").pagination("getCurrentPage"));
}
function borrowBook(BID, BUID) {
	$("#ConfirmDialogModal").modal("hide");
	$.ajax({
        type: "GET",
        url: "../Handle/BorrowHandlerService.ashx?method=Add_New_Borrow",
        data: {BID: BID, BUID: BUID},
        dataType: "json",
        success: function (data) {
        	//console.log(data);
            if (1 == data.MessageType) {
                initSearch();
            	$("#dialog-modal-label").text("借书成功！");
                $("#DialogModal").modal("show");
            } else {
            	$("#dialog-modal-label").text(data.MessageContent);
                $("#DialogModal").modal("show");
            }
        }
    });
}

function getBookListOutputHtml(items) {
    var outputHtml = "";
    if (items.length > 0) {
	    for (var i = 0; i < items.length; i++) {
	        var item = items[i];
            
	        //var dataContent = item["Author"] + " / " + item["PYM"] + " / " + item["Press"];// + subStrToLimitLength(item["Descript"], 150) + "</small>";
	        var btnContent = "<a href='#' class='btn btn-xs btn-danger borrow-btn' value='"+item["BID"]+"' BUID='"+item["UID"]+"'>借书</a>";
	        if ("1" == item["Cstatus"] || "2" == item["Cstatus"]) {
	        	btnContent = "<p style='margin-bottom:0px; height:22px;'><small>已借出</small></p>"
	        } else if ("1" == item["Flag"]) {
	        	btnContent = "<p style='margin-bottom:0px; height:22px;'><small>已下架</small></p>"
	        }
	        
	        outputHtml += "<div class='col-md-2 col-xs-6'>" +
	        "<div class='thumbnail' style='border: 0 none;'>" +
	            "<img src='" + item["Pname"] +
	            "' style='width: 120px;height: 148px;' alt='图书封面' class='thumbnail-img' value='"+item["BID"]+"' id='"+item["BID"]+"'>" +
	            "<div class='caption'>" +
	            "<p>" + subStrToLimitLength(item["Bname"], 6) + "</p>" +
	            "<p><small>" + subStrToLimitLength(item["Author"], 10) + "</small></p>" +
	            btnContent+
	            "</div>" +
	        "</div>" +
	        "</div>";
	    }
	}
    return outputHtml;
}

function getPageSize() {
    return 12;
}

function refreshCategoryBookList(PageIndex) {
    $('#category-book-list').html("<h4 class='text-center'>数据加载中请稍后。。。</h4>");
    var selectedCategoryId = "";
    if (Cookies.get('gxskSearchBookCategory')) {
        selectedCategoryId = Cookies.get('gxskSearchBookCategory');
    } else {
        $(".book-category").each(function(e) {
            if ($(this).hasClass("btn-primary")) {
                selectedCategoryId = $(this).val();
            }
        });
    }
	
    fetchBookListByCategoryId(selectedCategoryId, PageIndex, getPageSize());
}

function refreshSearchBookList(PageIndex) {
    $('#search-book-list').html("<h4 class='text-center'>数据加载中请稍后。。。</h4>");
    var oldPageIndex = 1;
    if (Cookies.get('gxskSearchBookNamePage')) {
         oldPageIndex = Cookies.get('gxskSearchBookNamePage');
    } else {
        oldPageIndex = PageIndex;
    }
    fetchBookListByBookName($("#book-name").val(), oldPageIndex, getPageSize());
}

function getPageNum() {  
    var pagenum = 1;
   var url = window.location.href;
   //console.log(url);
   if (url.indexOf("#") != -1) {  
      var str = url.split("#")[1]; 
      //console.log(str); 
      pagenum = str.split("-")[1];  
    
   }  
   return pagenum;  
}

function initSearch() {
    if (Cookies.get('gxskSearchWay') && "#search-by-name" == Cookies.get('gxskSearchWay')) {
        $("#book-name").val(Cookies.get('gxskSearchNameStr'));
        var pageNum = Cookies.get('gxskSearchBookNamePage')?Cookies.get('gxskSearchBookNamePage'):1;
        refreshSearchBookList(pageNum);
        $("#findBookTabs a[href='#search-by-name']").tab('show');
    } else {
        var pageNum = Cookies.get('gxskSearchBookCategoryPage')?Cookies.get('gxskSearchBookCategoryPage'):1;
        fetchCategoryList(pageNum);
        $("#findBookTabs a[href='#browse-by-category']").tab('show');
    }
}